package com.qitianyong.sgkusbcamera;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gkusbsdk.GKUSBCommand;
import com.gkusbsdk.GKUSBFileInfo;
import com.gkusbsdk.GKUSBSDK;
import com.ligo.log.util.ZyLog;
import com.qitianyong.adapter.RecycleAdapter;
import com.qitianyong.adapter.ViewPicViewPagerAdapter;
import com.qitianyong.decoder.HardDecoder;
import com.qitianyong.decoder.MJpegDecoder;
import com.qitianyong.extendUI.NoDragSeekBar;
import com.qitianyong.selfclass.BUS_MESSAGE;
import com.qitianyong.selfclass.BaseActivity;
import com.qitianyong.selfclass.CONSTANT;
import com.qitianyong.selfclass.ClickUtils;
import com.qitianyong.selfclass.GKDevice;
import com.qitianyong.selfclass.LogUtils;
import com.qitianyong.selfclass.MarginDecoration;
import com.qitianyong.selfclass.Message2EventBus;
import com.qitianyong.selfclass.PublicMethod;
import com.qitianyong.selfclass.VideoDataControl;
import com.qitianyong.selfclass.VideoDataControl.VideoData;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.sleep;

public class GalleryActivity extends BaseActivity implements RecycleAdapter.IClick, GKUSBSDK.CallBack, SurfaceHolder.Callback {

    public static final int MAX_LINE_ITEMS = 5;
    private static final int MSG_PROGRESS = 1;
    private static final int MSG_INVISIBLE_PLAYBACK_MASK = 2;
    private static final int MSG_VISIBLE_PLAYBACK_MASK = 3;

    private Button __btn_back, __btn_select;
    private TextView __tv_title;
    private RadioButton __btn_record, __btn_hurry, __btn_photo;
    private ImageButton __ib_lock, __ib_unlock, __ib_delete;
    private RelativeLayout __rl_operator;
    private boolean __bSelect = false;
    private boolean __bnormal = false;
    private SwipeRefreshLayout __srLayout;
    private RecyclerView __recyclerview;
    private RelativeLayout __rl_nofile;
    private RelativeLayout __rl_fullscreen_mask;
    private TextView __tv_tip;
    private RelativeLayout __rl_playback;
    private TextView __tv_videoname;
    private SurfaceView __sv_playback;
    private SurfaceHolder __sv_hodler;
    private TextView __tv_endtime;
    private NoDragSeekBar __sb_progress;
    private ImageButton __ib_play, __ib_next, __ib_privious;
    private ViewPager __rl_playphoto;
    private ImageButton __ib_large_playback;
    private ImageView __iv_default_playback;
    private TextView __tv_starttime;
    private View content1;
    private View content2;

    // data
    private int __file_type = GKUSBCommand.FILE_TYPE.CYCLE_FILE;
    private List<Object> __fileList = new ArrayList<>();
    private RecycleAdapter __adapter;
    private ViewPicViewPagerAdapter __viewPicViewPagerAdapter;
    private GridLayoutManager __gridLayoutManager;
    private int __last_visible = 0;
    private boolean __isLoading = false;
    private int __current_index = 0;
    private Handler __handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == MSG_PROGRESS) {
                int totaltime = __usbPlayFileInfo.__duration / 1000;
                if (totaltime > 1 && __bPlayback) {
                    int pos = __current_time * 100 / (totaltime);
                    __sb_progress.setProgress(pos);

                    int minute = __current_time / 60;
                    int second = __current_time % 60;
                    String time = PublicMethod.dataTo2Char(minute) + ":" +
                            PublicMethod.dataTo2Char(second);
                    __tv_starttime.setText(time);

                    if (pos == 100) {
                        __bPlayback = false;
                        __ib_play.setImageResource(R.drawable.btn_play_s);
                        __ib_large_playback.setVisibility(View.VISIBLE);
                        messsageBox(getString(R.string.tip_play_complete));
                        normalScreen();
                        // 此处时间可能有1秒的误差，结束时最后时间拷贝到开始时间
                        __tv_starttime.setText(__tv_endtime.getText());
                    }
                }
            } else if (msg.what == MSG_INVISIBLE_PLAYBACK_MASK) {
                if (!__bPlayback) {
                    __bPlayback = true;
                    __ib_play.setImageResource(R.drawable.btn_stop_s);
                    __ib_large_playback.setVisibility(View.INVISIBLE);
                }
                __iv_default_playback.setVisibility(View.INVISIBLE);
            } else if (msg.what == MSG_VISIBLE_PLAYBACK_MASK) {
                __iv_default_playback.setVisibility(View.VISIBLE);
            }
        }
    };
    private int __expect_number = 0;
    private int __operator_count = 0; //已操作完成个数
    private HardDecoder __decorder;

    private MJpegDecoder __mjpegDecoder;
    private GKUSBFileInfo __usbPlayFileInfo;
    private int __usbPlayPosition = 0;
    private int __current_time = 0;
    private boolean __bPlayback = false;
    private int __record_bak = GKUSBCommand.STATUS_RECORD.NORECORD_EXSIT_SD;
    private VideoDataControl videoDataControl = new VideoDataControl();
    private int maxHeight;
    private int maxWidth;
    private long decodeTime;

    protected static int created = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        created++;
        setContentView(R.layout.activity_gallery);
        if (isFinishing()) {
            return;
        }
        if (created > 1) {
            finish();
            return;
        }
        findView();
        setListener();

        initPopItem(CONSTANT.ITEM_FILE_TYPE.TYPE_CYCLE);
        initRecycleView();
        initViewPager();

        __record_bak = getIntent().getIntExtra("status", 0);

        __sv_hodler = __sv_playback.getHolder();
        __sv_hodler.addCallback(this);

        GKDevice.getInstance().setCallback(this);
        playThread.start();
        autoFinishThread.start();
    }

    // 删除刷新处理
    private void doDelUpdate() {
        if (__rl_fullscreen_mask.getVisibility() == View.VISIBLE) {
            __srLayout.setRefreshing(false);
            //return;
        }
        __srLayout.setRefreshing(true);
        __current_index = 0;

        __rl_fullscreen_mask.setVisibility(View.VISIBLE);
        __tv_tip.setText(getString(R.string.loading_down));

        Log.i("getfileinfo", "doDownUpdate:" + __current_index);

        // 发送请求设备名列表指令
        GKDevice.getInstance().setUSBFileInfoList(__fileList);
        if (GKDevice.__hDevice == 0) { //下拉失败，清理
            __fileList.clear();
            __adapter.notifyDataSetChanged();

            __srLayout.setRefreshing(false);
            __rl_nofile.setVisibility(View.VISIBLE);
            __rl_fullscreen_mask.setVisibility(View.INVISIBLE);
        } else {
            GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_SEARCH_FILE, __file_type);
            __rl_nofile.setVisibility(View.INVISIBLE);
        }

        __adapter.resetSelectedCount();
    }

    // 下拉刷新处理
    private void doDownUpdate() {
        if (__rl_fullscreen_mask.getVisibility() == View.VISIBLE) {
            __srLayout.setRefreshing(false);
            return;
        }
        __srLayout.setRefreshing(true);
        __current_index = 0;

        __rl_fullscreen_mask.setVisibility(View.VISIBLE);
        __tv_tip.setText(getString(R.string.loading_down));

        Log.i("getfileinfo", "doDownUpdate:" + __current_index);

        // 发送请求设备名列表指令
        GKDevice.getInstance().setUSBFileInfoList(__fileList);
        if (GKDevice.__hDevice == 0) { //下拉失败，清理
            __fileList.clear();
            __adapter.notifyDataSetChanged();

            __srLayout.setRefreshing(false);
            __rl_nofile.setVisibility(View.VISIBLE);
            __rl_fullscreen_mask.setVisibility(View.INVISIBLE);
        } else {
            GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_SEARCH_FILE, __file_type);
            __rl_nofile.setVisibility(View.INVISIBLE);
        }

        __adapter.resetSelectedCount();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
    }

    // 获取下一个选中项
    private int HandleNextSelectItem(int start_pos, int operator) {
        int i = start_pos - 1;
        for (; i != 0; i--) {
            Object obj = __fileList.get(i);
            if (obj instanceof GKUSBFileInfo) {
                GKUSBFileInfo fileInfo = (GKUSBFileInfo) obj;
                if (fileInfo.__select) {// 调出最新的选中项
                    int ret = -1;
                    if (operator == CONSTANT.FILE_OPERATOR.OPERATOR_DELETE) {
                        if (__file_type == GKUSBCommand.FILE_TYPE.PHOTO_FILE) {
                            ret = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_DELETE_PHOTO,
                                    fileInfo);
                        } else {
                            ret = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_DELETE_VIDEO,
                                    fileInfo);
                        }
                    } else if (operator == CONSTANT.FILE_OPERATOR.OPERATOR_LOCK) {
                        ret = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_LOCK_VIDEO,
                                fileInfo);
                    } else if (operator == CONSTANT.FILE_OPERATOR.OPERATOR_UNLOCK) {
                        ret = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_UNLOCK_VIDEO,
                                fileInfo);
                    }

                    if (ret == -1) {
                        return -1;
                    }

                    return i;
                }
            }
        }

        return 0;
    }

    // 初始化RecycleView
    private void initRecycleView() {

        __srLayout.post(new Runnable() {
            @Override
            public void run() {
                doDownUpdate();
            }
        });
        __srLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.i("GKDevice", "onRefresh");
                doDownUpdate();
            }
        });

        __recyclerview.addItemDecoration(new MarginDecoration(this));
        __recyclerview.setHasFixedSize(true);
        __gridLayoutManager = new GridLayoutManager(this, MAX_LINE_ITEMS);
        __gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {

                if (position + 1 > __fileList.size()) {
                    return MAX_LINE_ITEMS;
                }

                Object obj = __fileList.get(position);
                if (obj instanceof GKUSBFileInfo) {
                    return 1;
                }

                return MAX_LINE_ITEMS;
            }
        });

        __recyclerview.setLayoutManager(__gridLayoutManager);
        __adapter = new RecycleAdapter(this, __fileList);
        __recyclerview.setAdapter(__adapter);
        __adapter.setClickCallback(this);

        __recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                __last_visible = __gridLayoutManager.findLastVisibleItemPosition();

                int count = __adapter.getItemCount();
                if (__last_visible + 1 == count && dy > 0) {

                    boolean isRefreshing = __srLayout.isRefreshing();
                    if (isRefreshing) {
                        __adapter.notifyItemRemoved(__adapter.getItemCount());
                    }
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && __last_visible + 1 == __gridLayoutManager.getItemCount()
                        && __current_index != 0) {

                    Log.i("GKDevice", "-----------------111----------------");
                    if (__isLoading) return; // 请求时间可能需要1-2秒，这个时候去滑动很可能导致请求多次
                    __isLoading = true;     // 此处屏蔽掉这种情况

                    __rl_fullscreen_mask.setVisibility(View.VISIBLE);
                    __tv_tip.setText(getString(R.string.loading_down));
                    __adapter.setLoadStatus(CONSTANT.LOAD_STATUS.STATUS_LOADING);

                    Log.i("getfileinfo", "onScrollStateChanged:" + __current_index);
                    __expect_number = GKDevice.getInstance().GetNextFiles(__current_index, 10);
                    if (__expect_number > 0) {
                        __current_index += __expect_number;
                    } else {
                        messsageBox(getString(R.string.up_nomore));
                        __rl_fullscreen_mask.setVisibility(View.INVISIBLE);
                    }

                    __isLoading = false;
                    __handle.postDelayed(new Runnable() {
                        @Override
                        public void run() {// 仅仅是为了显示上拉效果
                            __adapter.setLoadStatus(CONSTANT.LOAD_STATUS.STATUS_FINISH);
                        }
                    }, 2000);
                }
            }
        });
    }

    private void initViewPager() {
        __viewPicViewPagerAdapter = new ViewPicViewPagerAdapter(__rl_playphoto);
        __rl_playphoto.setAdapter(__viewPicViewPagerAdapter);
    }

    private void findView() {

        __btn_back = (Button) findViewById(R.id.btn_back);
        __btn_record = (RadioButton) findViewById(R.id.btn_record);
        __btn_hurry = (RadioButton) findViewById(R.id.btn_hurry);
        __btn_photo = (RadioButton) findViewById(R.id.btn_photo);
        __tv_title = (TextView) findViewById(R.id.tv_title);

        __ib_lock = (ImageButton) findViewById(R.id.ib_lock);
        __ib_unlock = (ImageButton) findViewById(R.id.ib_unlock);
        __ib_delete = (ImageButton) findViewById(R.id.ib_delete);

        __rl_operator = (RelativeLayout) findViewById(R.id.rl_operator);
        __btn_select = (Button) findViewById(R.id.btn_select);
        __srLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
        __recyclerview = (RecyclerView) findViewById(R.id.recyclerView);

        __rl_nofile = (RelativeLayout) findViewById(R.id.rl_nofile);
        __rl_fullscreen_mask = (RelativeLayout) findViewById(R.id.rl_fullscreen_mask);
        __tv_tip = (TextView) findViewById(R.id.tv_tip);
        __rl_playback = (RelativeLayout) findViewById(R.id.rl_playback);
        __tv_videoname = (TextView) findViewById(R.id.tv_videoname);

        __sv_playback = (SurfaceView) findViewById(R.id.sv_playback);
        __tv_endtime = (TextView) findViewById(R.id.tv_endtime);
        __sb_progress = (NoDragSeekBar) findViewById(R.id.sb_progress);

        __ib_play = (ImageButton) findViewById(R.id.ib_play);
        __ib_next = (ImageButton) findViewById(R.id.ib_next);
        __ib_privious = (ImageButton) findViewById(R.id.ib_privious);

        __rl_playphoto = (ViewPager) findViewById(R.id.rl_playphoto);

        __ib_large_playback = (ImageButton) findViewById(R.id.ib_large_playback);
        __iv_default_playback = (ImageView) findViewById(R.id.iv_default_playback);

        __tv_starttime = (TextView) findViewById(R.id.tv_starttime);

        content1 = findViewById(R.id.content1);
        content2 = findViewById(R.id.content2);
        __sv_playback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                __bnormal = true;
                normalScreen();
            }
        });
        findViewById(R.id.full_screen).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                __bnormal = false;
                fullScreen();
            }
        });
    }

    //全屏播放视频放大
    RelativeLayout.LayoutParams normalScreenLayoutParams0;
    RelativeLayout.LayoutParams normalScreenLayoutParams1;
    RelativeLayout.LayoutParams normalScreenLayoutParams2;

    public void fullScreen() {
        RelativeLayout.LayoutParams fullScreenLayoutParams0 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        RelativeLayout.LayoutParams fullScreenLayoutParams1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        final RelativeLayout.LayoutParams fullScreenLayoutParams2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        if (normalScreenLayoutParams0 == null) {
            normalScreenLayoutParams0 = (RelativeLayout.LayoutParams) __rl_playback.getLayoutParams();
            normalScreenLayoutParams1 = (RelativeLayout.LayoutParams) content1.getLayoutParams();
            normalScreenLayoutParams2 = (RelativeLayout.LayoutParams) content2.getLayoutParams();
        }

        __rl_playback.setLayoutParams(fullScreenLayoutParams0);
        content1.setLayoutParams(fullScreenLayoutParams1);
        //content2.setLayoutParams(fullScreenLayoutParams2);
        //全屏有进度条，3s后自动消失进度条！
        content2.setLayoutParams(normalScreenLayoutParams2);
        findViewById(R.id.full_screen).setVisibility(View.INVISIBLE);
        __handle.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (__bnormal == true) {
                    __bnormal = false;
                    content2.setLayoutParams(normalScreenLayoutParams2);
                } else {
                    content2.setLayoutParams(fullScreenLayoutParams2);
                    __bnormal = true;
                }

            }
        }, 3000);
    }

    //正常播放视频
    public void normalScreen() {
        if (normalScreenLayoutParams0 != null) {
            __rl_playback.setLayoutParams(normalScreenLayoutParams0);
            content1.setLayoutParams(normalScreenLayoutParams1);
            content2.setLayoutParams(normalScreenLayoutParams2);
        }
        findViewById(R.id.full_screen).setVisibility(View.VISIBLE);
    }

    private void setListener() {

        __btn_back.setOnClickListener(mListener);
        __btn_record.setOnClickListener(mListener);
        __btn_hurry.setOnClickListener(mListener);
        __btn_photo.setOnClickListener(mListener);

        __ib_lock.setOnClickListener(mListener);
        __ib_unlock.setOnClickListener(mListener);
        __ib_delete.setOnClickListener(mListener);

        __btn_select.setOnClickListener(mListener);
        __ib_play.setOnClickListener(mListener);
        __ib_next.setOnClickListener(mListener);
        __ib_privious.setOnClickListener(mListener);
        __ib_large_playback.setOnClickListener(mListener);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Message2EventBus message) {

        switch (message.__what) {
            case BUS_MESSAGE.BUS_SEARCH_COMPLETE: {
                // 搜索完成后，请求20个文件的信息
                __srLayout.setRefreshing(false);

                int value = (int) message.object;
                if (value == -1) { // 请求失败
                    messsageBox(getString(R.string.refresh_err));
                    __rl_nofile.setVisibility(View.VISIBLE);
                    __rl_fullscreen_mask.setVisibility(View.INVISIBLE);

                } else if (value == 0) {
                    __rl_nofile.setVisibility(View.VISIBLE);
                    __rl_fullscreen_mask.setVisibility(View.INVISIBLE);
                } else {

                    Log.i("getfileinfo", "onEventMainThread:" + __current_index);
                    __expect_number = GKDevice.getInstance().GetNextFiles(__current_index, 30);
                    if (__expect_number > 0) {
                        __current_index += __expect_number;
                    }
                }

                break;
            }
            case BUS_MESSAGE.BUS_CLEAR_FILELIST: { // 清理链表

                __fileList.clear();
                __adapter.notifyDataSetChanged();
                break;
            }
            case BUS_MESSAGE.BUS_FILEINFO_OK: {
                if (__expect_number <= 0) { // 防错
                    break;
                }

                if (--__expect_number == 0) {
                    __rl_fullscreen_mask.setVisibility(View.INVISIBLE);
                    if (__file_type == GKUSBCommand.FILE_TYPE.PHOTO_FILE) {
                        GKDevice.getInstance().getFileImg();
                    }
                } else {
                    __tv_tip.setText(__expect_number + getString(R.string.loading));
                }

                Log.i("GKDevice", "left count:" + __expect_number);
                __adapter.notifyDataSetChanged();
                break;
            }
            case BUS_MESSAGE.BUS_DELETE_PHOTO: {
                __current_index = HandleNextSelectItem(__current_index--,
                        CONSTANT.FILE_OPERATOR.OPERATOR_DELETE);
                if (__current_index == 0) {
                    messsageBox(getString(R.string.delete_ok));
                    __srLayout.post(new Runnable() {
                        @Override
                        public void run() {
                            PublicMethod.sleep(1000);
                            doDelUpdate();
                        }
                    });
                } else {
                    String tip = (++__operator_count) + "/" + __adapter.getCurrentSelectedCount()
                            + getString(R.string.deleteing);
                    __tv_tip.setText(tip);
                }
                break;
            }
            case BUS_MESSAGE.BUS_DELETE_VIDEO: {

                __current_index = HandleNextSelectItem(__current_index--,
                        CONSTANT.FILE_OPERATOR.OPERATOR_DELETE);
                if (__current_index == 0) {
                    messsageBox(getString(R.string.delete_ok));
                    __srLayout.post(new Runnable() {
                        @Override
                        public void run() {
                            PublicMethod.sleep(1000);
                            doDelUpdate();
                        }
                    });
                } else {
                    String tip = (++__operator_count) + "/" + __adapter.getCurrentSelectedCount()
                            + getString(R.string.deleteing);
                    __tv_tip.setText(tip);
                }
                break;
            }
            case BUS_MESSAGE.BUS_LOCK_VIDEO: {
                __current_index = HandleNextSelectItem(__current_index--,
                        CONSTANT.FILE_OPERATOR.OPERATOR_LOCK);
                if (__current_index == 0) {
                    messsageBox(getString(R.string.lock_ok));
                    __srLayout.post(new Runnable() {
                        @Override
                        public void run() {
                            PublicMethod.sleep(1000);
                            doDelUpdate();
                        }
                    });
                } else {
                    String tip = (++__operator_count) + "/" + __adapter.getCurrentSelectedCount()
                            + getString(R.string.locking);
                    __tv_tip.setText(tip);
                }
                break;
            }
            case BUS_MESSAGE.BUS_UNLOCK_VIDEO: {
                __current_index = HandleNextSelectItem(__current_index--,
                        CONSTANT.FILE_OPERATOR.OPERATOR_UNLOCK);
                if (__current_index == 0) {
                    messsageBox(getString(R.string.unlock_ok));
                    __srLayout.post(new Runnable() {
                        @Override
                        public void run() {
                            PublicMethod.sleep(1000);
                            doDelUpdate();
                        }
                    });
                } else {
                    String tip = (++__operator_count) + "/" + __adapter.getCurrentSelectedCount()
                            + getString(R.string.unlocking);
                    __tv_tip.setText(tip);
                }
                break;
            }
            case BUS_MESSAGE.BUS_DELETE_PHOTO_ERR:
            case BUS_MESSAGE.BUS_DELETE_VIDEO_ERR: {
                String name = (String) message.object;
                messsageBox(name + " " + getString(R.string.delete_err));
                __rl_fullscreen_mask.setVisibility(View.INVISIBLE);

                __srLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        PublicMethod.sleep(1000);
                        doDownUpdate();
                    }
                });
                break;
            }
            case BUS_MESSAGE.BUS_LOCK_VIDEO_ERR: {
                String name = (String) message.object;
                messsageBox(name + " " + getString(R.string.lock_err));
                __rl_fullscreen_mask.setVisibility(View.INVISIBLE);

                __srLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        PublicMethod.sleep(1000);
                        doDownUpdate();
                    }
                });
                break;
            }
            case BUS_MESSAGE.BUS_UNLOCK_VIDEO_ERR: {
                String name = (String) message.object;
                messsageBox(name + " " + getString(R.string.unlock_err));
                __rl_fullscreen_mask.setVisibility(View.INVISIBLE);

                __srLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        PublicMethod.sleep(1000);
                        doDownUpdate();
                    }
                });
                break;
            }
            case BUS_MESSAGE.BUS_PLAYBACK_ERR: {
                __bPlayback = false;
                __ib_play.setImageResource(R.drawable.btn_play_s);
                __ib_large_playback.setVisibility(View.VISIBLE);
                __ib_next.setClickable(true);
                __ib_privious.setClickable(true);
                break;
            }
            case BUS_MESSAGE.BUS_PLAYBACK: {
                __bPlayback = true;
                __ib_play.setImageResource(R.drawable.btn_stop_s);
                __ib_large_playback.setVisibility(View.INVISIBLE);
                __ib_next.setClickable(true);
                __ib_privious.setClickable(true);
                break;
            }
            case BUS_MESSAGE.BUS_STOP_PLAYBACK_ERR: {

                break;
            }
            case BUS_MESSAGE.BUS_STOP_PLAYBACK: {
                __bPlayback = false;
                __ib_play.setImageResource(R.drawable.btn_play_s);
                break;
            }
            case BUS_MESSAGE.BUS_PAUSE_PLAYBACK_ERR: {
                __bPlayback = true;
                __ib_play.setImageResource(R.drawable.btn_stop_s);
                __ib_large_playback.setVisibility(View.INVISIBLE);
                break;
            }
            case BUS_MESSAGE.BUS_PAUSE_PLAYBACK: {
                __bPlayback = false;
                __ib_play.setImageResource(R.drawable.btn_play_s);
                __ib_large_playback.setVisibility(View.VISIBLE);
                break;
            }
            case BUS_MESSAGE.BUS_RESUME_PLAYBACK_ERR: {
                __bPlayback = false;
                __ib_play.setImageResource(R.drawable.btn_play_s);
                __ib_large_playback.setVisibility(View.VISIBLE);
                break;
            }
            case BUS_MESSAGE.BUS_RESUME_PLAYBACK: {
                __bPlayback = true;
                __ib_play.setImageResource(R.drawable.btn_stop_s);
                __ib_large_playback.setVisibility(View.INVISIBLE);
                break;
            }
            case BUS_MESSAGE.BUS_SMALL_PHOTO_ERR: {
                String name = (String) message.object;
                messsageBox(name + getString(R.string.playback_err));
                break;
            }
            case BUS_MESSAGE.BUS_SMALL_PHOTO: {
                if (__rl_playphoto.getVisibility() == View.VISIBLE || __file_type == GKUSBCommand.FILE_TYPE.PHOTO_FILE) {
                    if (__rl_playphoto.findViewWithTag(message.object) != null) {
                        __rl_playphoto.getAdapter().notifyDataSetChanged();
                    }
                    if (__recyclerview.findViewWithTag(message.object) != null) {
                        __adapter.notifyDataSetChanged();
                    }
                }
                break;
            }
            case BUS_MESSAGE.BUS_OFFLINE: {
                __iv_default_playback.setVisibility(View.VISIBLE);
                __bPlayback = false;
                __ib_play.setImageResource(R.drawable.btn_play_s);
                __sb_progress.setProgress(0);

                // 当正在加载时断线
                __expect_number = 0;
                __srLayout.setRefreshing(false);
                __rl_fullscreen_mask.setVisibility(View.INVISIBLE);
                messsageBox(getString(R.string.tip_offline));
                break;
            }
            default:
                break;
        }
    }

    private void changeSelectStatus() {
        if (__bSelect) {
            __rl_operator.setVisibility(View.INVISIBLE);
            __btn_select.setText(getString(R.string.select));

            // 复原
            for (Object obj : __fileList) {
                if (obj instanceof GKUSBFileInfo) {
                    GKUSBFileInfo info = (GKUSBFileInfo) obj;
                    info.__select = false;
                }
            }

            __adapter.setAdapterMode(CONSTANT.FILELIST_MODE.MODE_PLAY);
            __adapter.notifyDataSetChanged();
            __bSelect = false;
        } else {
            __rl_operator.setVisibility(View.VISIBLE);
            __btn_select.setText(getString(R.string.cancel));

            __adapter.setAdapterMode(CONSTANT.FILELIST_MODE.MODE_SELECTOR);
            __bSelect = true;
        }
    }

    private View.OnClickListener mListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //防止短时间内多次点击
            if (ClickUtils.isFastClick()) {
                //直接return不能防止radiobutton的状态改变
                if (v.getId() == R.id.btn_hurry ||
                        v.getId() == R.id.btn_record ||
                        v.getId() == R.id.btn_photo) {
                    switch (__file_type) {
                        case GKUSBCommand.FILE_TYPE.CYCLE_FILE:
                            __btn_record.setChecked(true);
                            break;
                        case GKUSBCommand.FILE_TYPE.HURRY_FILE:
                            __btn_hurry.setChecked(true);
                            break;
                        case GKUSBCommand.FILE_TYPE.PHOTO_FILE:
                            __btn_photo.setChecked(true);
                            break;
                    }
                }
                return;
            }
            LogUtils.addClickLog(v.getId());

            switch (v.getId()) {
                case R.id.btn_back: {
                    if (releaseResource(true)) {
                        finish();
                    }
                    break;
                }
                case R.id.btn_record: {
                    if (__file_type == GKUSBCommand.FILE_TYPE.CYCLE_FILE) {
                        return;
                    }

                    __tv_title.setText(getString(R.string.cycle_record));
                    initPopItem(CONSTANT.ITEM_FILE_TYPE.TYPE_CYCLE);
                    __file_type = GKUSBCommand.FILE_TYPE.CYCLE_FILE;
                    break;
                }
                case R.id.btn_hurry: {
                    if (__file_type == GKUSBCommand.FILE_TYPE.HURRY_FILE) {
                        return;
                    }

                    __tv_title.setText(getString(R.string.hurry_record));
                    initPopItem(CONSTANT.ITEM_FILE_TYPE.TYPE_HUNRY);
                    __file_type = GKUSBCommand.FILE_TYPE.HURRY_FILE;
                    break;
                }
                case R.id.btn_photo: {
                    if (__file_type == GKUSBCommand.FILE_TYPE.PHOTO_FILE) {
                        return;
                    }

                    __tv_title.setText(getString(R.string.pictures));
                    initPopItem(CONSTANT.ITEM_FILE_TYPE.TYPE_PHOTO);
                    __file_type = GKUSBCommand.FILE_TYPE.PHOTO_FILE;
                    break;
                }
                case R.id.ib_lock: {
                    if (__fileList.size() == 0) {
                        messsageBox(getString(R.string.tip_nofile));
                        break;
                    }

                    __current_index = HandleNextSelectItem(__fileList.size(),
                            CONSTANT.FILE_OPERATOR.OPERATOR_LOCK);
                    if (__current_index == 0) {
                        messsageBox(getString(R.string.no_select_item));
                    } else {
                        __rl_fullscreen_mask.setVisibility(View.VISIBLE);
                        __operator_count = 0;
                        int currentSelectedCount = __adapter.getCurrentSelectedCount();
                        if (currentSelectedCount != 1) {
                            String tip = (++__operator_count) + "/" + currentSelectedCount
                                    + getString(R.string.locking);
                            __tv_tip.setText(tip);
                        } else {
                            __tv_tip.setText(getString(R.string.locking));
                        }
                    }
                    break;
                }
                case R.id.ib_unlock: {
                    if (__fileList.size() == 0) {
                        messsageBox(getString(R.string.tip_nofile));
                        break;
                    }

                    __current_index = HandleNextSelectItem(__fileList.size(),
                            CONSTANT.FILE_OPERATOR.OPERATOR_UNLOCK);
                    if (__current_index == 0) {
                        messsageBox(getString(R.string.no_select_item));
                    } else {
                        __rl_fullscreen_mask.setVisibility(View.VISIBLE);
                        __operator_count = 0;
                        int currentSelectedCount = __adapter.getCurrentSelectedCount();
                        if (currentSelectedCount != 1) {
                            String tip = (++__operator_count) + "/" + currentSelectedCount
                                    + getString(R.string.unlocking);
                            __tv_tip.setText(tip);
                        } else {
                            __tv_tip.setText(getString(R.string.unlocking));
                        }
                    }
                    break;
                }
                case R.id.ib_delete: {
                    if (__fileList.size() == 0) {
                        messsageBox(getString(R.string.tip_nofile));
                        break;
                    }

                    __current_index = HandleNextSelectItem(__fileList.size(),
                            CONSTANT.FILE_OPERATOR.OPERATOR_DELETE);
                    if (__current_index == 0) {
                        messsageBox(getString(R.string.no_select_item));
                    } else {
                        __rl_fullscreen_mask.setVisibility(View.VISIBLE);
                        __operator_count = 0;
                        int currentSelectedCount = __adapter.getCurrentSelectedCount();
                        if (currentSelectedCount != 1) {
                            String tip = (++__operator_count) + "/" + currentSelectedCount
                                    + getString(R.string.deleteing);
                            __tv_tip.setText(tip);
                        } else {
                            __tv_tip.setText(getString(R.string.deleteing));
                        }
                    }
                    break;
                }
                case R.id.btn_select: {
                    changeSelectStatus();
                    __adapter.resetSelectedCount();
                    break;
                }
                case R.id.ib_large_playback:
                case R.id.ib_play: {
                    if (__sb_progress.getProgress() == 100) { // 已经播放完成，重播
                        videoDataControl.clear();
                        GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_PLAYBACK, __usbPlayFileInfo);
                        break;
                    }

                    if (__bPlayback) {
                        GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_PAUSE_PLAYBACK, __usbPlayFileInfo);
                    } else {
                        GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_RESUME_PLAYBACK, __usbPlayFileInfo);
                    }

                    break;
                }
                case R.id.ib_next: {
                    int size = __fileList.size();
                    if (__usbPlayPosition >= size) {
                        messsageBox(getString(R.string.tip_lastfile));
                        break;
                    }

                    int i = ++__usbPlayPosition;
                    for (; i < size; i++) {
                        Object obj = __fileList.get(i);
                        if (obj instanceof GKUSBFileInfo) {
                            PlayFileByPosition(i);
                            break;
                        }
                    }

                    break;
                }
                case R.id.ib_privious: {
                    if (__usbPlayPosition <= 0) {
                        messsageBox(getString(R.string.tip_firstfile));
                        break;
                    }

                    int i = --__usbPlayPosition;
                    for (; i > 0; i--) {
                        Log.i("GKDevice", "list size:" + __fileList.size() + " index:" + i);
                        Object obj = __fileList.get(i);
                        if (obj instanceof GKUSBFileInfo) {
                            PlayFileByPosition(i);
                            break;
                        }
                    }

                    if (i == 0) {
                        messsageBox(getString(R.string.tip_firstfile));
                    }
                    break;
                }
                default:
                    break;
            }

            // 文件请求
            if (v.getId() == R.id.btn_hurry ||
                    v.getId() == R.id.btn_record ||
                    v.getId() == R.id.btn_photo) {

                if (__bSelect) {
                    changeSelectStatus();
                }
                GKDevice.getInstance().clearSpeciallyTypeCommand(CONSTANT.COMMAND.CMD_GET_PHOTO);
                if (__rl_playback.getVisibility() == View.VISIBLE) {
                    PlaybackVisible(View.INVISIBLE);
                    if (__usbPlayFileInfo != null) {
                        videoDataControl.clear();
                        GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_STOP_PLAYBACK, __usbPlayFileInfo);
                    }
                    /*if(__record_bak == GKUSBCommand.STATUS_RECORD.RECORDING) {
                        PublicMethod.sleep(500);
                        GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_OPEN_RECORD, null);
                    }*/
                }

                if (__rl_playphoto.getVisibility() == View.VISIBLE) {
                    PlayPhotoVisible(View.INVISIBLE);
                }

                __srLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        doDownUpdate();
                    }
                });
            }
        }
    };

    public void initPopItem(int type) {
        switch (type) {
            case CONSTANT.ITEM_FILE_TYPE.TYPE_CYCLE: {

                __ib_lock.setVisibility(View.VISIBLE);
                __ib_unlock.setVisibility(View.GONE);
                __ib_delete.setVisibility(View.VISIBLE);
                break;
            }
            case CONSTANT.ITEM_FILE_TYPE.TYPE_HUNRY: {

                __ib_lock.setVisibility(View.GONE);
                __ib_unlock.setVisibility(View.VISIBLE);
                __ib_delete.setVisibility(View.GONE);
                break;
            }
            case CONSTANT.ITEM_FILE_TYPE.TYPE_PHOTO: {
                __ib_lock.setVisibility(View.GONE);
                __ib_unlock.setVisibility(View.GONE);
                __ib_delete.setVisibility(View.VISIBLE);
                break;
            }
            default:
                break;
        }
    }

    private void messsageBox(String message) {
        if (__toast != null) {
            __toast.cancel();
        }

        __toast = Toast.makeText(GalleryActivity.this, message, Toast.LENGTH_SHORT);
        __toast.show();
    }

    long lastTouchTime = System.currentTimeMillis();

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        lastTouchTime = System.currentTimeMillis();
        return super.dispatchTouchEvent(ev);
    }

    Thread autoFinishThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!GalleryActivity.this.isFinishing()) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (__expect_number != 0 || __srLayout.isRefreshing()) {
                    lastTouchTime = System.currentTimeMillis();
                    continue;
                }

                if (__bPlayback) {
                    lastTouchTime = System.currentTimeMillis();
                    continue;
                }
                if (System.currentTimeMillis() - lastTouchTime > 30000) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            boolean ret = releaseResource(false);
                            if (!ret) {
                                ret = releaseResource(false);
                            }
                            if (!ret) {
                                ret = releaseResource(false);
                            }
                            finish();
                        }
                    });


                }


            }
        }
    });

    private boolean releaseResource(boolean showHint) {
        if (__rl_playphoto.getVisibility() == View.VISIBLE) {
            PlayPhotoVisible(View.INVISIBLE);
            return false;
        }

        if (__rl_playback.getVisibility() == View.VISIBLE) {
            PlaybackVisible(View.INVISIBLE);
            if (__usbPlayFileInfo != null) {
                videoDataControl.clear();
                GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_STOP_PLAYBACK, __usbPlayFileInfo);
            }

            return false;
        }

        if (__expect_number != 0 || __srLayout.isRefreshing()) {
            if (showHint)
                messsageBox(getString(R.string.loading_can_t_exit));
            return false;
        }

        if (__bSelect) {
            changeSelectStatus();
            __adapter.resetSelectedCount();
            return false;
        }
        GKDevice.getInstance().clearSpeciallyTypeCommand(CONSTANT.COMMAND.CMD_GET_PHOTO);
        GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_EXIT_FILELIST, null);

        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        created--;
        if (__record_bak == GKUSBCommand.STATUS_RECORD.RECORDING) {
            PublicMethod.sleep(500);
            GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_OPEN_RECORD, null);
        }
    }

    @Override
    public void onBackPressed() {
        if (releaseResource(true)) {
            super.onBackPressed();
        }
    }

    private void PlaybackVisible(int visible) {
        normalScreen();
        __rl_playback.setVisibility(visible);

        if (visible == View.VISIBLE) {
            visible = View.INVISIBLE;
        } else {
            visible = View.VISIBLE;
        }

        __tv_title.setVisibility(visible);
        __btn_select.setVisibility(visible);
        __srLayout.setVisibility(visible);
    }

    private void PlayPhotoVisible(int visible) {

        __rl_playphoto.setVisibility(visible);

        if (visible == View.VISIBLE) {
            visible = View.INVISIBLE;
        } else {
            visible = View.VISIBLE;
        }

        __tv_title.setVisibility(visible);
        __btn_select.setVisibility(visible);
        __srLayout.setVisibility(visible);
    }

    private void PlayPhotoByPosition(int pos) {
        GKUSBFileInfo fileInfo = (GKUSBFileInfo) (__fileList.get(pos));

        __usbPlayFileInfo = fileInfo;
        __usbPlayPosition = pos;

        __viewPicViewPagerAdapter.setPics(__fileList, pos);

        int ret = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_GET_PHOTO, fileInfo);
        if (ret == -1) {
            messsageBox(getString(R.string.playback_err));
        }
    }

    private void PlayFileByPosition(int pos) {

        __ib_next.setClickable(false);
        __ib_privious.setClickable(false);
        GKUSBFileInfo fileInfo = (GKUSBFileInfo) (__fileList.get(pos));
        __tv_videoname.setText(new String(fileInfo.__name));

        int hour = fileInfo.__duration / 60000;
        int minute = fileInfo.__duration / 1000 % 60;

        String endTime = PublicMethod.dataTo2Char(hour) + ":" + PublicMethod.dataTo2Char(minute);
        __tv_endtime.setText(endTime);
        __tv_starttime.setText(PublicMethod.dataTo2Char(0) + ":" + PublicMethod.dataTo2Char(0));
        __sb_progress.setProgress(0);
        __iv_default_playback.setVisibility(View.VISIBLE);
        __ib_play.setImageResource(R.drawable.btn_play_s);
        // 发送播放请求
        __usbPlayFileInfo = fileInfo;
        __usbPlayPosition = pos;
        videoDataControl.clear();
        int ret = GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_PLAYBACK, fileInfo);
        if (ret == -1) {
            messsageBox(getString(R.string.playback_err));
            __ib_next.setClickable(true);
            __ib_privious.setClickable(true);
        }
    }

    @Override
    public void onItemClick(View v, int position, int mode, int select_count) {
        if (mode == CONSTANT.FILELIST_MODE.MODE_SELECTOR) {
            if (__toast != null) __toast.cancel();
            if (select_count == 0) {
                __toast = Toast.makeText(this, getString(R.string.cancel_all), Toast.LENGTH_SHORT);

            } else {
                __toast = Toast.makeText(this, select_count + getString(R.string.select_count), Toast.LENGTH_SHORT);
            }
            __toast.show();
        } else if (mode == CONSTANT.FILELIST_MODE.MODE_PLAY) {

            if (__file_type == GKUSBCommand.FILE_TYPE.PHOTO_FILE) {
                PlayPhotoVisible(View.VISIBLE);
                PlayPhotoByPosition(position);
            } else {
                //去掉下载文件 防止堵塞播放视频
                GKDevice.getInstance().clearSpeciallyTypeCommand(CONSTANT.COMMAND.CMD_GET_PHOTO);
                // 播放
                PlaybackVisible(View.VISIBLE);
                PlayFileByPosition(position);
            }
        }
    }

    Thread playThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!GalleryActivity.this.isFinishing()) {
                int sleep = 40 - decodeTime > 0 ? (int) (40 - decodeTime) : 0;
                PublicMethod.sleep(sleep);
                VideoData first = null;
                if (!__bPlayback) {
                    continue;
                }
                synchronized (VideoData.class) {
                    if (!videoDataControl.isEmpty()) {
                        first = videoDataControl.getFirst();
                        videoDataControl.removeFirst();
                    }
                }
                if (first == null) {
                    continue;
                }
                long time = System.currentTimeMillis();
                deocedData(first);
                decodeTime = System.currentTimeMillis() - time;
//                Log.d("HardDecoder",decodeTime+"");
            }

        }
    });

    private void deocedData(VideoData videoData) {
        synchronized (GalleryActivity.class) {
            if (maxHeight != videoData.height || maxWidth != videoData.width) {
                if (__decorder != null) {
                    __decorder.Destroy();
                }
                maxHeight = videoData.height;
                maxWidth = videoData.width;
//                __decorder = new HardDecoder(maxWidth,
//                        maxHeight, __sv_hodler.getSurface());
                __mjpegDecoder = new MJpegDecoder(__sv_hodler.getSurface(), __sv_playback.getWidth(), __sv_playback.getHeight());
            }
        }
        if (__decorder != null) {
//            boolean decoder = __decorder.Decoder(videoData.data, videoData.length);
//            ZyLog.d("Decoder =" + decoder);
            __mjpegDecoder.decodeFrame(videoData.data);
            //容错  返回的时间可能会与视频时长差一秒或者末尾有一帧倒数第二秒的数据
            if (__current_time != videoData.time) {
                __current_time = videoData.time;
                __handle.sendEmptyMessage(MSG_PROGRESS);
                if (__usbPlayFileInfo != null &&
                        __usbPlayFileInfo.__duration / 1000 - 1 == __current_time) {
                    __handle.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (__bPlayback &&
                                    __usbPlayFileInfo != null &&
                                    __usbPlayFileInfo.__duration / 1000 - 1 == __current_time) {
                                __current_time = __usbPlayFileInfo.__duration / 1000;
                                __handle.sendEmptyMessage(MSG_PROGRESS);
                            }
                        }
                    }, 1100);
                }
            }
        }

    }

    @Override
    public void cb_stream(long hUSBDevice, byte[] data, int length, int width, int height, int time) {
//        ZyLog.d("hUSBDevice =" + hUSBDevice +" width="+width+ " height=" + height + " length=" + length + " time=" + time);
        synchronized (VideoData.class) {
            if (time >= 0) {
                videoDataControl.addLast(new VideoData(data, length, time, width, height));
            }
        }
//        Log.i("scroll", "time:"+time);
        if (time == 1) {
            //因未播放前一秒数据，且在time=1时就隐藏遮罩层，会显示黑屏或者上一次播放的画面。故添加300ms延时，
            __handle.sendEmptyMessage(MSG_INVISIBLE_PLAYBACK_MASK);
        } else if (time == 0) {
            __handle.sendEmptyMessage(MSG_VISIBLE_PLAYBACK_MASK);
        }
    }

    @Override
    public void surfaceCreated(final SurfaceHolder holder) {
        synchronized (GalleryActivity.class) {
            //播放线程自动创建decode
            maxHeight = -1;
            maxWidth = -1;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (__decorder != null)
            __decorder.Destroy();
    }
}
